﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Factory
{
    public partial class SaidaContribuidor : Form
    {

        double valorFactory = 0;
        double valorDecrementar = 0;
        Int32 id = 0;

        public SaidaContribuidor()
        {
            InitializeComponent();
        }

        private void SaidaContribuidor_Load(object sender, EventArgs e)
        {
            CarregarSocios();
        }

        IList<Socio> lstSocio = new List<Socio>();
        private void CarregarSocios()
        {
            try
            {
                SocioDAO SocioDAO = new SocioDAO();
                lstSocio = SocioDAO.obtemListaSocios();
                var lista = from c in lstSocio
                            select new
                            {
                                ID=c.ID,
                                Nome=c.Nome,
                                CPF=c.CPF,
                                CapitalInvestido=c.CapitalInvestido,
                                PercentualFactory = c.PercentualFactory
                            };

                dataGridSocio.DataSource = lista.ToList();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



        protected override bool ProcessCmdKey(ref Message message, Keys keys)
        {
            switch (keys)
            {
                case Keys.Escape:
                    //Process action here.
                    MenuPrincipal menu = new MenuPrincipal();
                    menu.Show();
                    this.Hide();
                    return false;
            }

            return false;
        }

        private void dataGridSocio_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //verifico se o grid há linhas selecionadas
                if (dataGridSocio.CurrentRow != null)
                {
                    //capturo o codigo da grid
                    int cod = Convert.ToInt32(dataGridSocio.CurrentRow.Cells[0].Value);

                    //recupero o Socio que desejo alterar
                    var Socio = lstSocio.SingleOrDefault(x => x.ID == cod);

                    //insiro seus valores nos controles
                    
                    txtNome.Text = Socio.Nome;
                    txtmCPF.Text = Socio.CPF;
                    txtPercentualFactory.Text = Convert.ToString(Socio.PercentualFactory);
                    txtCapitalInvestido.Text = Convert.ToString(Socio.CapitalInvestido);
                    id = Socio.ID;

                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //inicio pega valor atual da factory
            try
            {
                DAOBase m_cnn = new DAOBase();

                #region Query
                string query =
                    @"SELECT ValorAtual FROM Factory where ID = 1;";
                #endregion

                SqlCommand cmd = new SqlCommand(query, m_cnn.CreateConnection());

                SqlDataReader dr = cmd.ExecuteReader();

                int valor = dr.GetOrdinal("ValorAtual");

                dr.Read();

                valorFactory = dr.GetDouble(valor); // salva valor atual da factory
                txtValorAtualFactory.Text = Convert.ToString(valorFactory);
                //double valoratual = ValorFactory + CapitalInvestido; //incrementa valor atual da factory
                //fim pega valor atual da factory

                valorDecrementar = Convert.ToDouble ((valorFactory/100) * Convert.ToDouble(txtPercentualFactory.Text));

                txtCapitalReceber.Text = Convert.ToString(valorDecrementar);
                


            }
                       catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            
        }

        private void btnEfetuarSaida_Click(object sender, EventArgs e)
        {
            int resultado = 0;

            double valoratual1 = valorFactory - valorDecrementar;

            DAOBase m_cnn1 = new DAOBase();
            //inicio update do valor atual da factory
            #region query
            string query1 = @"UPDATE Factory SET ValorAtual = @ValorAtual WHERE ID = 1";

            #endregion

            SqlCommand cmd1 = new SqlCommand(query1, m_cnn1.CreateConnection());
            cmd1.Parameters.Add(new SqlParameter("ValorAtual", valoratual1));

            resultado = cmd1.ExecuteNonQuery();

            m_cnn1.DestroyConnection();
            //fim update do valor atual da factory


            
            DAOBase m_cnn2 = new DAOBase();
            //inicio update do valor atual da factory
            #region query2
            string query2 = @"Delete from Socio where ID = @IDSOCIO";

            #endregion

            SqlCommand cmd2 = new SqlCommand(query2, m_cnn2.CreateConnection());
            cmd2.Parameters.Add(new SqlParameter("IDSOCIO", id));

            resultado = cmd2.ExecuteNonQuery();

            m_cnn1.DestroyConnection();


            CarregarSocios();
            Utils.LimpaCampos(this);

            MessageBox.Show("Socio removido!");

        }

        private void btnVoltar_Click(object sender, EventArgs e)
        {
            MenuPrincipal menu = new MenuPrincipal();
            menu.Show();
            this.Close();
        }
    }
}
